<template>
    <!-- 登录弹窗 -->
    <n-modal v-model:show="isShowLogin">
        <n-card
            style="width: 638px;"
            :bordered="false"
            size="huge"
            role="dialog"
            aria-modal="true"
            class="login-card"
        > 
            <template #header>
                <div class="flex justify-end">
                    <n-icon class="cursor-pointer" :size="28" color="#000" :component="Close" @click="isShowLogin = false" />
                </div>
            </template>
            <div class="flex flex-col items-center">
                <p class="text-2xl text-[#00102F] font-600 mb-32px">登录</p>
                <div class="-ml-110px">
                    <n-tabs size="large" animated v-model:value="tabName">
                        <n-tab-pane name="mobile" tab="手机号登录"></n-tab-pane>
                        <n-tab-pane name="idcard" tab="身份证登录"></n-tab-pane>
                    </n-tabs>
                </div>
                <n-form 
                    class="login-form" 
                    ref="loginRef" 
                    :model="loginForm" 
                    :rules="loginRules"
                    label-placement="left" 
                    :label-width="80"
                    require-mark-placement="left"
                    v-if="tabName == 'mobile'"
                >
                    <n-form-item label="手机号" path="mobile">
                        <n-input v-model:value="loginForm.mobile" placeholder="输入手机号" />
                    </n-form-item>
                    <n-form-item label="验证码" path="code">
                        <n-input v-model:value="loginForm.code" placeholder="输入验证码">
                            <template #suffix>
                                <span class="text-[#0063FF] text-base cursor-pointer" @click="getMobileCode" v-if="!codeTimer">获取验证码</span>
                                <span class="text-[#0063FF] text-base" v-else>{{ codeTime }}s</span>
                            </template>
                        </n-input>
                    </n-form-item>
                    <n-form-item class="pl-80px mt-6">
                        <n-button class="w-full h-48px" type="info" :loading="loginLoading" @click="submitLogin">登录</n-button>
                    </n-form-item>
                </n-form>

                <div class="mt-3 mb-7 relative" v-else>
                    <img class="w-320px h-152px" :src="bgCard01" alt="">
                    <img class="w-170px h-170px absolute -right-85px top-0" :src="bgCard02" alt="">

                    <div class="flex flex-col items-center mt-17px">
                        <span class="text-[#00102F] text-base">请将身份证放置在感应区</span>
                        <span class="text-[#00102F] text-base">识别成功后自动登录</span>
                    </div>
                </div>
            </div>
        </n-card>
    </n-modal>
</template>

<script lang="ts" setup>
    import { loginSms, loginApi, postUserIdCardLogin } from "@/api/user"
    import { useUserStore } from "@/store/modules/user"
    import { Close } from "@vicons/ionicons5"
    import validateList from "@/utils/formValidate"
    import bgCard01 from "@/assets/image/icon/bg-idcard.png"
    import bgCard02 from "@/assets/image/icon/bg-to-card.png"

    const userStore = useUserStore()
    const { userInfo, token } = storeToRefs(userStore)

    const isShowLogin = ref(false)

    const tabName = ref('mobile')

    const loginForm = reactive({
        mobile: '',
        code: ''
    })

    const loginRef = ref()
    const codeTime = ref(60)

    const loginRules = {
        mobile: {
            key: 'mobile',
            required: true,
            trigger: ['blur', 'input'],
            validator: (rule:any, value:string) => {
               return !!value && validateList.checkPhone(value)
            },
            renderMessage: () => {
                return validateList.checkPhoneMsg(loginForm.mobile)
            }
        },
        code: {
            required: true,
            message: '请输入验证码',
            trigger: ['blur', 'input']
        }
    }
    
    const openModal = () => {
        isShowLogin.value = true
    }

    const closeModal = () => {
        isShowLogin.value = false
    }

    // 获取手机验证码
    const codeTimer = ref<NodeJS.Timeout | null>(null)
    const getMobileCode = async () => {
        loginRef.value?.validate(async (err:any) => {
            if(err) {
                console.error(err)
            }else {
                codeTimer.value = setInterval(() => {
                    if(codeTime.value == 0) {
                        clearInterval(Number(unref(codeTimer)))
                        codeTimer.value = null
                        codeTime.value = 60
                        return
                    }
                    codeTime.value--
                }, 1000)
                await loginSms({mobile: loginForm.mobile})
            }
        }, (rule) => {
            return rule?.key === 'mobile'
        })
    }

    watch(() => isShowLogin.value, (newVal) => {
        if(!newVal) {
            if(unref(codeTimer)) {
                clearInterval(Number(unref(codeTimer)))
                codeTimer.value = null
                loginRef.value?.restoreValidation()
            }

            codeTime.value = 60

            unref(websockets) && websockets.value.close()
        }else {
            tabName.value = 'mobile'
        }
    })

    // 监听身份证登录
    const websockets = ref<any>(null)
    watch(() => tabName.value, (newVal) => {
        if(newVal == 'idcard') {
            idCardLogin()
        }else {
            unref(websockets) && websockets.value.close()
        }
    })

    const loginLoading = ref(false)
    const submitLogin = async () => {
        loginRef.value?.validate(async (err) => {
            if(!err) {
                loginLoading.value = true
                const res:any = await loginApi({...loginForm})
                if(res.code == 400) return window['$message'].error(res.msg)
                window['$message'].success('登录成功')
                userInfo.value = res
                token.value = res.token
                window.postMessage({type: "LOGIN_OK", content: res}, "*")
                isShowLogin.value = false
                loginLoading.value = false
            }
        })
    }

    function idCardLogin() {
        websockets.value = new WebSocket('ws:127.0.0.1:7415');

        websockets.value.onopen = (event) => {
            console.log(`<----- websockets.onopen ----->`, event);
            websockets.value.send("02?timeout=10000");
        }

        websockets.value.onclose = (event) => {
            console.log(`<----- websockets.onclose ----->`, event);
        }

        websockets.value.onmessage = (event) => {
            const alldata = event.data.split("|");

            /**姓名 */
            const partyName = alldata[1];
            /**性别 */
            const gender = alldata[2];
            /**民族 */
            const nation = alldata[3];
            /**出生日期 */
            const bornDay = alldata[4];
            /**住址 */
            const certAddress = alldata[5];
            /**身份证号 */
            const certNumber = alldata[6];
            /**签发机关 */
            const certOrg = alldata[7];
            /**开始期限 */
            const effDate = alldata[8];
            /**结束期限 */
            const expDate = alldata[9];
            /**照片 */
            const avatar = `data:image/bmp;base64,${alldata[17]}`;

            if (alldata.length >= 17) {
                const data = {
                    partyName,
                    gender,
                    nation,
                    bornDay,
                    certAddress,
                    certNumber,
                    certOrg,
                    effDate,
                    expDate,
                    avatar,
                }

                console.log(`read success: `, data);
                
                postUserIdCardLogin(certNumber, partyName).then(res => {
                    if(res.code == 400) return window['$message'].error(res.msg)
                    window['$message'].success('登录成功')
                    userInfo.value = res
                    token.value = res.token
                    window.postMessage({type: "LOGIN_OK", content: res}, "*")
                    isShowLogin.value = false
                })
                // MessageUtil.send("service-worker")({
                //     type: PEOPLE_LOGIN_CARD, content: {
                //         id_card: certNumber,
                //         name: partyName,
                //     }
                // }).then((res) => {
                //     if (res.code === 400) return window['$message'].error(res.msg);
                //     StorageUtil.set("people_login_result", res);
                //     window['$message'].success({ type: "success", message: "提示", description: "身份证登录成功" });
                // })
            }
            else {
                const data = event.data;
                console.log(`read fail: `, data);
            }
        }
    }

    defineExpose({
        openModal,
        closeModal
    })
</script>

<style lang="scss" scoped>
.login-form {
    width: 80%;
    padding-right: 30px;
    margin-left: -30px;
    margin-top: 8px;

    ::v-deep(.n-form-item-label) {
        min-height: 48px !important;
    }

    ::v-deep(.n-input__input-el) {
        height: 48px;
    }
}

.login-card {
    ::v-deep(.n-card-header) {
        padding: 16px;
    }

    ::v-deep(.n-tabs-bar) {
        height: 5px;
    }

    ::v-deep(.n-tabs-tab__label) {
        font-size: 17px;
    }
}
</style>